//
//  HOBigImageViewer.m
//  Huahai
//
//  Created by Fox Guo on 4/8/14.
//
//

#import "HOBigImageViewer.h"
#import "Logger.h"
#import "UIImageView+WebCache.h"

@interface HOSingleBigImageViewer()
@property (nonatomic, copy)SDWebImageCompletionBlock downloadBlock;
@end
@implementation HOSingleBigImageViewer
- (id)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
		
		imageView.contentMode = UIViewContentModeScaleAspectFit;
        // add gesture recognizers to the image view
        _singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
        _doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
        
//        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
        
        [_doubleTap setNumberOfTapsRequired:2];
        
        _pinchGuesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinch:)];
        _singleLongTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongTap:)];
        
        _panGuesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
        
        [self addGestureRecognizer:_panGuesture];
        [self addGestureRecognizer:_pinchGuesture];
        [self addGestureRecognizer:_singleTap];
        [self addGestureRecognizer:_doubleTap];
        [self addGestureRecognizer:_singleLongTap];
        
        float minimumScale = [self frame].size.width  / [imageView frame].size.width;
        [self setMinimumZoomScale:minimumScale];
        self.maximumZoomScale = 2.0f;
        [self setZoomScale:minimumScale];
        [self addSubview:imageView];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        self.delegate = self;
		[self initIndicateUI];
		
		
		self.downloadBlock = ^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
		{
			self.image = image;
		};
    }
 
	return self;
}
- (void)initIndicateUI
{
	loadingView = [[UIActivityIndicatorView alloc]init];
	[loadingView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:.4]];
	[loadingView setColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:.8]];
	loadingView.layer.cornerRadius = 4;
	loadingView.frame = CGRectMake((self.frame.size.width - 50) / 2, (self.frame.size.height - 50) / 2, 50, 50);
	[self addSubview:loadingView];
}
- (void)dealloc
{
	self.downloadBlock = nil;
	[self removeGestureRecognizer:_panGuesture];
	[self removeGestureRecognizer:_pinchGuesture];
	[self removeGestureRecognizer:_singleTap];
	[self removeGestureRecognizer:_doubleTap];
	[self removeGestureRecognizer:_singleLongTap];
	_panGuesture.delegate = nil;
	[_panGuesture release];
	_singleTap.delegate = nil;
	[_singleTap release];
	_pinchGuesture.delegate = nil;
	[_pinchGuesture release];
	_singleLongTap.delegate = nil;
	[_singleLongTap release];
    [imageView release];
	if(loadingView)
	{
		[loadingView release];
		loadingView = nil;
	}
	self.imagePath = nil;
    [super dealloc];
}
- (void)panAction:(UIPanGestureRecognizer *)sender {
    //得到拖的过程中的xy坐标
    if(((int)(self.zoomScale + 0.005)) == 1)
    {
        [self panGesture:sender];
        return;
    }
    CGPoint translation=[(UIPanGestureRecognizer*)sender translationInView:self];
    //平移图片CGAffineTransformMakeTranslation
//    imageView.transform = CGAffineTransformMakeTranslation(netTranslation.x + translation.x, netTranslation.y+translation.y);

    CGFloat offsetWidth = (imageView.frame.size.width - self.frame.size.width) / 2;
    CGFloat offsetHeight = (imageView.frame.size.height - self.frame.size.height) / 2;
    CGFloat positionX = netTranslation.x + translation.x;
    CGFloat positionY = netTranslation.y + translation.y;
    if(offsetWidth <= 0 && offsetHeight <=0)
    {
        return;
    }
    else if(offsetWidth <= 0 && offsetHeight > 0)
    {
        positionX = 0;
        if(positionY > offsetHeight)
        {
            positionY = offsetHeight;
        }
        else if(positionY <  -offsetHeight)
        {
            positionY = -offsetHeight;
        }
    }
    else if(offsetWidth > 0 && offsetHeight <= 0)
    {
        positionX = 0;
        if(positionX > offsetWidth)
        {
            positionX = offsetWidth;
        }
        else if(positionX <  -offsetWidth)
        {
            positionX = -offsetWidth;
        }
        
    }
    else if(offsetWidth > 0 && offsetHeight > 0)
    {
        if(positionX > offsetWidth)
        {
            positionX = offsetWidth;
        }
        else if(positionX <  -offsetWidth)
        {
            positionX = -offsetWidth;
        }
        
        if(positionY > offsetHeight)
        {
            positionY = offsetHeight;
        }
        else if(positionY <  -offsetHeight)
        {
            positionY = -offsetHeight;
        }
    }
    
    
    
    
        
        imageView.frame = CGRectMake(positionX, positionY, imageView.frame.size.width, imageView.frame.size.height);

    
//    LogNor(@"translation x:%f, translation.y:%f",translation.x,translation.y);
//    LogNor(@"imageView.x:%f, y:%f, width:%f, height:%f", imageView.frame.origin.x, imageView.frame.origin.y, imageView.frame.size.width, imageView.frame.size.height);
    //状态结束，保存数据
    if(sender.state==UIGestureRecognizerStateEnded){
        netTranslation.x+=translation.x;
        netTranslation.y+=translation.y;
    }
}
- (void)displayLoadingView:(BOOL)isLoading
{
	loadingView.hidden = !isLoading;
	if(isLoading && !loadingView.isAnimating)
	{
		[loadingView startAnimating];
	}
	else if(!isLoading && loadingView.isAnimating)
	{
		[loadingView stopAnimating];
	}
	
}
- (void)setData:(NSObject *)imgData
{
	if([imgData isKindOfClass:[UIImage class]])
	{
		self.image = (UIImage *)imgData;
		imageView.image = (UIImage *)imgData;
//		imageView.layer.borderWidth = 4;
//		imageView.layer.borderColor = [UIColor greenColor].CGColor;
		
	}
	else
	{
		[imageView sd_setImageWithURL:[NSURL URLWithString:(NSString *)imgData]
					 placeholderImage:[UIImage imageNamed:@"morentu"]
							  options:SDWebImageCacheMemoryOnly
							completed:self.downloadBlock];
//		
//		[imageView sd_setImageWithURL:[NSURL URLWithString:(NSString *)imgData]
//					 placeholderImage:[UIImage imageNamed:@"morentu"]//[UIImage imageNamed:@"bg_btn_blog_image_default"]
//							completed:self.downloadBlock];
	}
}

- (UIImage *)getImageData
{
    return self.image;
}

#pragma mark UIScrollViewDelegate methods

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return imageView;
}
- (void) pinch:(UIPinchGestureRecognizer *) recognizer {
//    LogNor(@"pinch:");
    CGPoint anchor = [recognizer locationInView:imageView];
    anchor = CGPointMake(anchor.x - imageView.bounds.size.width/2, anchor.y-imageView.bounds.size.height/2);
    
    CGAffineTransform affineMatrix = imageView.transform;
    affineMatrix = CGAffineTransformTranslate(affineMatrix, anchor.x, anchor.y);
    affineMatrix = CGAffineTransformScale(affineMatrix, [recognizer scale], [recognizer scale]);
    affineMatrix = CGAffineTransformTranslate(affineMatrix, -anchor.x, -anchor.y);
    imageView.transform = affineMatrix;
    
    [recognizer setScale:1];
}
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale {
//    LogNor(@"scrollViewDidEndZooming:");
    [scrollView setZoomScale:scale+0.01 animated:NO];
    [scrollView setZoomScale:scale animated:NO];
}
- (void)handleDoubleTap:(UIGestureRecognizer *)recognizer {
//    LogNor(@"handleDoubleTap:");
    // double tap zooms in
//    CGRect rect = CGRectMake(0,0, _image.size.width, _image.size.height);
//    [self zoomToRect:rect animated:YES];
   imageView.frame = CGRectMake(0,0, imageView.frame.size.width, imageView.frame.size.height);
    
//    LogNor(@"imageView.x:%f, y:%f, width:%f, height:%f", imageView.frame.origin.x, imageView.frame.origin.y, imageView.frame.size.width, imageView.frame.size.height);
//    imageView.transform = CGAffineTransformMakeTranslation(0, 0);
    netTranslation = CGPointMake(0, 0);
    if(self.zoomScale > self.minimumZoomScale)
        [self setZoomScale:self.minimumZoomScale animated:YES];
    else
        [self setZoomScale:self.maximumZoomScale animated:YES];
    
    [self stopTimeoutTimer];
//    LogNor(@"imageView.x:%f, y:%f, width:%f, height:%f", imageView.frame.origin.x, imageView.frame.origin.y, imageView.frame.size.width, imageView.frame.size.height);
}
#pragma mark TapDetectingImageViewDelegate methods
- (void)handleLongTap:(UILongPressGestureRecognizer *)gestureRecognizer
{
//    LogNor(@"handleLongTap:");
    if([self.bigImageViewerDelegate respondsToSelector:@selector(longPress:)])
    {
        [self.bigImageViewerDelegate longPress:gestureRecognizer];
    }
}
- (void)panGesture:(UIPanGestureRecognizer *)gestureRecognizer
{
//    LogNor(@"panGesture:");
    if([self.bigImageViewerDelegate respondsToSelector:@selector(panGesture:)])
    {
        [self.bigImageViewerDelegate panGesture:gestureRecognizer];
    }
}
- (void)handleSingleTap:(UITapGestureRecognizer *)gestureRecognizer {
    // single tap does nothing for now
    
//    LogNor(@"handleSingleTap:");
    if(timeoutTimer == nil)
    {
        timeoutTimer = [NSTimer scheduledTimerWithTimeInterval: .2
                                                 target: self
                                                      selector: @selector(handleTimeoutTimer:)
                                               userInfo: nil
                                                repeats: YES];

    }
    
}
- (void)stopTimeoutTimer
{
    [timeoutTimer invalidate];
    timeoutTimer = nil;
}

- (void)handleTimeoutTimer:(NSTimer *)timer
{
    
    if(self.bigImageViewerDelegate != nil && [self.bigImageViewerDelegate respondsToSelector:@selector(tapGesture)])
    {
        [self.bigImageViewerDelegate tapGesture];
    }
}
#pragma mark Utility methods

@end



@interface HOBigImageViewer()
{
	
}

@property(nonatomic, retain)NSArray *imageList;
@property (nonatomic ,assign) int imageIndex;
@property (nonatomic, retain)HOSingleBigImageViewer *currentSlide;
@property (nonatomic, retain)HOSingleBigImageViewer *leftSlide;
@property (nonatomic, retain)HOSingleBigImageViewer *rightSlide;
@end
@implementation HOBigImageViewer
- (id)initWithFrame:(CGRect)frame andData:(NSArray *)images andImageindex:(int)imgindex
{
    self = [super initWithFrame:frame];
    if (self) {
		
		self.imageList = images;
		slideArray = [[NSMutableArray alloc] init];
        self.leftSlide = [[[HOSingleBigImageViewer alloc]initWithFrame:CGRectMake(- frame.size.width,
																			 0,
																			 frame.size.width,
																			 frame.size.height)] autorelease];
        self.currentSlide = [[[HOSingleBigImageViewer alloc]initWithFrame:CGRectMake(0,
																				0,
																				frame.size.width,
																				frame.size.height)] autorelease];
//        currentSlide.layer.borderWidth = 2.0;
        self.rightSlide = [[[HOSingleBigImageViewer alloc]initWithFrame:CGRectMake(frame.size.width,
																			  0,
																			  frame.size.width,
																			  frame.size.height)] autorelease];
        self.currentSlide.bigImageViewerDelegate = self;
        self.rightSlide.bigImageViewerDelegate = self;
        self.leftSlide.bigImageViewerDelegate = self;
        [self addSubview:self.leftSlide];
        [self addSubview:self.currentSlide];
        [self addSubview:self.rightSlide];
		[slideArray addObject:self.leftSlide];
		[slideArray addObject:self.currentSlide];
		[slideArray addObject:self.rightSlide];
		
		
//        UIImage *image = [UIImage imageNamed:@"bg_btn_blog_image_default"];
        [self.currentSlide superview].clipsToBounds = YES;
        self.currentSlide.contentMode = UIViewContentModeScaleAspectFit;
        self.rightSlide.contentMode = UIViewContentModeScaleAspectFit;
        self.leftSlide.contentMode = UIViewContentModeScaleAspectFit;
		[self.currentSlide setData:[self.imageList objectAtIndex:imgindex]];
		[self setTotalWithTotalIndex:[self.imageList count] startIndex:imgindex];
        
    }
    return self;
}

- (void)dealloc
{
    self.currentSlide.bigImageViewerDelegate = nil;
    self.rightSlide.bigImageViewerDelegate = nil;
    self.leftSlide.bigImageViewerDelegate = nil;
	[slideArray removeAllObjects];
	[slideArray release];
	slideArray = nil;
	self.currentSlide = nil;
	self.leftSlide = nil;
	self.rightSlide = nil;
//	
//    [leftSlide release];
//    [currentSlide release];
//	[rightSlide release];
	[super dealloc];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/



//- (void)initGesture
//{
//
//    UITapGestureRecognizer *tap;
//    UIPanGestureRecognizer *pan;
//    pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
//    tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
//    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
//    
//    
//    
//    [tap requireGestureRecognizerToFail:pan];
//    
//    [self addGestureRecognizer:tap];
//    [self addGestureRecognizer:pan];
//    [self addGestureRecognizer:longPress];
//    tap.delegate = self;
//    [tap release];
//    [pan release];
//    [longPress release];
//}

- (void)longPress:(UILongPressGestureRecognizer *)longPress
{
//    LogNor(@"longPress");
    if([self.delegate respondsToSelector:@selector(longPress:withImageData:)])
    {
		
        [self.delegate longPress:longPress withImageData:[self.currentSlide getImageData]];
    }
}
- (void)tapGesture
{
    if([self.delegate respondsToSelector:@selector(imageViewerDidClose)])
    {
        [self.delegate imageViewerDidClose];
    }
}


- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

- (void)checkSwitchSatus:(SWITCH_STATUE)switchStatus
{
    
}

static CGFloat translation = 0;
-(void)panGesture:(UIPanGestureRecognizer *)recognizer
{
    
    if(isAnimating)
        return;
    
    if(totalIndex == 1)
        return;
    
    static BOOL hasFailed;
    static BOOL initialized;
    
    
    translation = [recognizer translationInView:self].x;
    LogImp(@"tra:%f", translation);
    if(translation > 0)
    {
        if(!canPrevious)
            return;
    }
    if(translation < 0)
    {
        if(!canNext)
            return;
    }
    if((translation> 0 && switchStatus == STADY_THE_LEFT) || (translation < 0 && switchStatus == STADY_THE_RIGHT))
    {
//        LogNor(@"in the left or right");
        return;
    }
    switch (recognizer.state) {
            
//            LogNor(@"gesture");
            
        case UIGestureRecognizerStateBegan:
        {
//            LogNor(@"UIGestureRecognizerStateBegan");
			hasFailed = NO;
			initialized = NO;
        }
            break;
        case UIGestureRecognizerStateChanged:{
//            LogNor(@"UIGestureRecognizerStateChanged");
			if (hasFailed) {
				return;
			}
            
            CGPoint location = [recognizer locationInView:self.currentSlide];
            
            if (location.y < 0 || location.y > self.currentSlide.frame.size.height || ![self isValide]) {
                hasFailed = YES;
                return;
            }
            
            
            [self updateIndex];
            if(!initialized)
            {
                if(translation > 0)
                {
                    [self leftSlideWillDisplay];
                }
                else
                {
                    [self rightSlideWillDisplay];
                }
                initialized = YES;
            }
            
            
            
            
            hasFailed = NO;
            self.currentSlide.frame = CGRectMake(translation, 0, self.currentSlide.frame.size.width, self.currentSlide.frame.size.height);
            [self moveGoRight:translation > 0];
            
            
            break;
        }
        case UIGestureRecognizerStateFailed:
        {
//            LogNor(@"UIGestureRecognizerStateFailed");
            [self switchPage:STADY_THE_MIDDLE isFromPanEvent:YES];
            break;
        }
        case UIGestureRecognizerStateRecognized:
        {
//            LogNor(@"UIGestureRecognizerStateRecognized");
            if(hasFailed)
            {
                [self switchPage:STADY_THE_MIDDLE isFromPanEvent:YES];
                return;
            }
            
            if (fabs((translation + [recognizer velocityInView:self.currentSlide].x / 4) / self.currentSlide.bounds.size.width) > 0.5) {
                
				if(translation > 0)
                {
                    [self switchPage:STADY_THE_RIGHT isFromPanEvent:YES];
                }
                else if(translation < 0)
                {
                    [self switchPage:STADY_THE_LEFT isFromPanEvent:YES];
                }
                else
                {
                    [self switchPage:STADY_THE_MIDDLE isFromPanEvent:YES];
                }
			} else {
				
                [self switchPage:STADY_THE_MIDDLE isFromPanEvent:YES];
			}
            
            
            
            break;
        }
        default:
            break;
    }
}
- (void)updateIndex
{

}
- (void)moveGoRight:(SWITCH_STATUE)isGoRight
{
    self.rightSlide.frame = CGRectMake(self.currentSlide.frame.origin.x + self.currentSlide.frame.size.width, 0, self.rightSlide.frame.size.width, self.rightSlide.frame.size.height);
    self.leftSlide.frame = CGRectMake(self.currentSlide.frame.origin.x - self.currentSlide.frame.size.width, 0, self.leftSlide.frame.size.width, self.leftSlide.frame.size.height);
    
}

- (void)switchPage:(SWITCH_STATUE)switchType isFromPanEvent:(BOOL)isFromPanEvent
{
    [UIView animateWithDuration:.3f
                     animations:^
     {
         isAnimating = YES;
         CGFloat cx = - self.currentSlide.frame.size.width;
         CGFloat rx = 0;
         CGFloat lx = - 2 *self.currentSlide.frame.size.width;
         if(!isFromPanEvent)
         {
             //if event from swipe, need notify subslide view viewWillDisplay when animation, pan event not need this, because this will be do in draging.
             
             [self updateIndex];
             if(switchType == STADY_THE_RIGHT)
             {
                 [self leftSlideWillDisplay];
             }
             else
             {
                 [self rightSlideWillDisplay];
             }
         }
         
         if(switchType == STADY_THE_RIGHT)
         {
             lx = 0;
             cx = self.currentSlide.frame.size.width;
             rx = 2 * self.self.currentSlide.frame.size.width;
         }
         else if(switchType == STADY_THE_MIDDLE)
         {
             lx = - self.currentSlide.frame.size.width;
             cx = 0;
             rx =self. self.currentSlide.frame.size.width;
         }
         else if(switchType == STADY_THE_LEFT)
         {
             lx = - 2 *self.currentSlide.frame.size.width;
             cx =  - self.currentSlide.frame.size.width;
             rx = 0;
             
         }
         self.currentSlide.frame = CGRectMake(cx, 0, self.currentSlide.frame.size.width,  self.currentSlide.frame.size.height);
         self.rightSlide.frame   = CGRectMake(rx, 0, self.rightSlide.frame.size.width,    self.rightSlide.frame.size.height);
         self.leftSlide.frame    = CGRectMake(lx, 0, self.leftSlide.frame.size.width,     self.leftSlide.frame.size.height);
         
         
         
     }
                     completion:^(BOOL finished)
     {
         
         CGFloat cx = self.currentSlide.frame.origin.x;
         CGFloat rx = self.rightSlide.frame.origin.x;
         CGFloat lx = self.leftSlide.frame.origin.x;
         
         
         if(switchType == STADY_THE_RIGHT)
         {
             rx = - self.currentSlide.frame.size.width;
             
             
         }
         else if(switchType == STADY_THE_LEFT)
         {
             lx =  self.currentSlide.frame.size.width;
             
         }
         self.currentSlide.frame = CGRectMake(cx, 0, self.currentSlide.frame.size.width,  self.currentSlide.frame.size.height);
         self.rightSlide.frame   = CGRectMake(rx, 0, self.rightSlide.frame.size.width,    self.rightSlide.frame.size.height);
         self.leftSlide.frame    = CGRectMake(lx, 0, self.leftSlide.frame.size.width,     self.leftSlide.frame.size.height);
         
         
         HOSingleBigImageViewer *tempView1 = self.leftSlide;
         HOSingleBigImageViewer *tempView2 = self.currentSlide;
         HOSingleBigImageViewer *tempView3 = self.rightSlide;
         
         if(switchType == STADY_THE_RIGHT)
         {
             self.leftSlide = tempView3;
             self.currentSlide = tempView1;
             self.rightSlide = tempView2;
             [self calculateIndexForNext:NO];
         }
         else if(switchType == STADY_THE_LEFT)
         {
             
             self.leftSlide = tempView2;
             self.currentSlide = tempView3;
             self.rightSlide = tempView1;
             [self calculateIndexForNext:YES];
         }
//         [currentSlide viewDidDisplay];
//         LogNor(@"%d/%d", currentIndex, totalIndex);
         //         if(switchType != STADY_THE_MIDDLE)
         [self updateIndex];
         
         [self updateData];
//         [slideDelegate didSlideDisplay:switchStatus currentIndex:currentIndex total:totalIndex currentView:[self getCurrentView]];
         isAnimating = NO;
         
     }];
}

- (BOOL)isValide
{
    return YES;
//    if(superView != nil)
//        return YES;
//    if(currentSlide.superview != nil)
//    {
//        superView = currentSlide.superview;
//        return YES;
//    }
//    
//    if(rightSlide.superview != nil)
//    {
//        superView = rightSlide.superview;
//        return YES;
//    }
//    if(leftSlide.superview != nil)
//    {
//        superView = leftSlide.superview;
//        return YES;
//    }
//    return superView != nil;
    
}
- (void)switchToLeft
{
    if(!canPrevious || isAnimating  || totalIndex <= 1)
        return;
    //    return;
    //    LogNor(@"switch from left");
    if(![self isValide] || switchStatus == STADY_THE_LEFT || switchStatus == STADY_SPECIAL)
        return;
    //    [self switchForNext:NO];
    [self switchPage:STADY_THE_RIGHT isFromPanEvent:NO];
}
- (void)switchToRight
{
    
    if(!canNext || isAnimating || totalIndex <= 1)
        return;
    //    LogNor(@"switch from right");
    if(![self isValide] || switchStatus == STADY_THE_RIGHT || switchStatus == STADY_SPECIAL)
        return;
    //    [self switchForNext:YES];
    [self switchPage:STADY_THE_LEFT isFromPanEvent:NO];
    
}
- (void)switchForNext:(BOOL)isNext
{
    //    [self calculateIndexForNext:isNext];
    //    [self switchSlideForNext:isNext];
    isNext ? [self switchToRight] : [self switchToLeft];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void)setTotalWithTotalIndex:(NSInteger)total startIndex:(NSInteger)startIndex
{
    
    totalIndex = total;
    canPrevious = NO;
    if(totalIndex ==0)
    {
        isDisable = YES;
        canPrevious = NO;
        canNext = NO;
        return;
    }
    isDisable = NO;
    
    if(startIndex < 0)
    {
        totalIndex = 0;
        startIndex = 0;
    }
    if(startIndex >= (totalIndex - 1))
    {
        startIndex = totalIndex - 1;
    }
    
    currentIndex = startIndex;
    canNext = currentIndex < (totalIndex - 1);
    canPrevious = currentIndex > 0;
    
    
    [self updateIndex];
    
    [self updateSwitchStatus];
    [self updateData];
}

- (void)calculateIndexForNext:(BOOL)isAdd
{
    if(isAdd)
    {
        currentIndex ++;
        [self updateSwitchStatus];
    }
    else
    {
        currentIndex --;
        [self updateSwitchStatus];
    }
}
- (HOSingleBigImageViewer *)getRightView
{
    return self.rightSlide;
}


- (HOSingleBigImageViewer *)getLeftView
{
    return self.leftSlide;
}
- (void)updateSwitchStatus
{
    if(totalIndex <= 1)
    {
        switchStatus = STADY_SPECIAL;
        currentIndex = 0;
        return;
    }
    
    
    if(currentIndex >= (totalIndex - 1))
    {
        currentIndex = totalIndex - 1;
        switchStatus = STADY_THE_RIGHT;
    }
    else if(currentIndex <= 0)
    {
        currentIndex = 0;
        switchStatus = STADY_THE_LEFT;
    }
    else
    {
        switchStatus = STADY_THE_MIDDLE;
    }
    [self updateIndex];
    
    
    
//    LogNor(@"currentIndex:%d", currentIndex);
    
}
//- (void)switchSlideForNext:(BOOL)isNext
//{
//
//    if(![self isValide])
//        return;
//    // remove the current view and replace with myView1
//    [currentSlide viewWillDisplay];
//    [firstSlide removeFromSuperview];
//    [secondSlide removeFromSuperview];
//    if(currentSlide == firstSlide)
//    {
//        currentSlide = secondSlide;
////        nextSlide = firstSlide;
//
//    }
//    else
//    {
//        currentSlide = firstSlide;
////        nextSlide = secondSlide;
//
//    }
//    currentSlide.currentIndex = currentIndex;
//    [currentSlide viewWillDisappear];
//    [superView addSubview:currentSlide];
//
//    // set up an animation for the transition between the views
//    CATransition *animation = [CATransition animation];
//    [animation setDuration:0.2];
//    [animation setType:kCATransitionPush];
//    [animation setSubtype:isNext ? kCATransitionFromRight : kCATransitionFromLeft];
//    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
//    
//    [[superView layer] addAnimation:animation forKey:@"SwitchToView2"];
//    
//}

- (void)updateData
{
    NSObject *currentBlogImg = [self.imageList objectAtIndex:currentIndex];
    [self.currentSlide setData:currentBlogImg];
    [self leftSlideWillDisplay];
    [self rightSlideWillDisplay];
	
	if([self.delegate respondsToSelector:@selector(updateCurrentIndex:total:)])
	{
		[self.delegate updateCurrentIndex:(currentIndex + 1) total:totalIndex];
	}
}
- (void)leftSlideWillDisplay
{
    if(currentIndex > 0)
    {
        NSString *previousBlogImg = [self.imageList objectAtIndex:currentIndex - 1];
        [self.leftSlide setData:previousBlogImg];
        canNext = YES;
    }
}
- (void)rightSlideWillDisplay
{
    if(currentIndex < ([self.imageList count] - 1))
    {
        NSString *nextBlogImg = [self.imageList objectAtIndex:currentIndex + 1];
        [self.rightSlide setData:nextBlogImg];
        canPrevious = YES;
    }
}

@end
